import {fetchLogin} from "./request";
import queryString from "./querystring";
import CookieUtil from "./cookie";
import axios from "axios";
import {isObject} from "lodash";
const location = window.location;
export function getLogin() {
    return new Promise(async (resolve, reject) => {
        const parsed = queryString.parse();
        const kgLoginTicket = parsed.kgLoginTicket;
        const opd = window.localStorage.getItem("opd");
        // const userName = CookieUtil.get("userName");
        const result = await fetchLogin("/login", {
            callbackUrl: document.domain + location.pathname,
            kgLoginTicket: kgLoginTicket,
            opd: opd
        });
        const res = result.data;
        console.log(res)
        if (res.status == 0) {
          if(!kgLoginTicket) {
            //location.href = res.redirectUrl;
          }
            //location.href = res.redirectUrl;
        } else {
            const token = res.token;
            const userData = res.userInfo;
            if (userData) {
                window.localStorage.setItem(
                    "opd",
                    isObject(userData) ? JSON.stringify(userData) : userData
                );
            }
            window.localStorage.setItem("fxams-token", token);
            resolve();
        }
    });
}

export function cleanInfo() {
    CookieUtil.del("userName", "/", ".kugou.net", 0);

    window.localStorage.removeItem("fxams-token");
    window.localStorage.removeItem("opd");
}
export function logout() {
    cleanInfo();

    location.href =
        "http://opd.kugou.net/common/signinApi.php?appId=v1-59f6a2253c62a&url=" +
        encodeURIComponent("http://" + location.host);
}

export const validateToken = function() {
    return new Promise(async (resolve, reject) => {
        try {
            const result = await axios
                .create({
                    headers: {
                        authorization: "Bearer " + window.localStorage.getItem("fxams-token")
                    }
                })
                .post("/validateToken");
            const res = result.data;
            if (res.status == 1) {
                resolve(true);
            } else {
                reject();
            }
        } catch (error) {
            reject();
        }
    });
};
